package com.opdar.athena.client.agent.controllers;


import com.opdar.athena.base.RedisSessionManager;
import com.opdar.athena.client.agent.annotations.Commond;
import com.opdar.athena.client.agent.annotations.MessageType;
import com.opdar.athena.client.agent.base.TcpSessionManager;
import com.opdar.athena.client.agent.server.IoSession;
import com.opdar.athena.entities.MessageEntity;
import com.opdar.athena.entities.ProjectEntity;
import com.opdar.athena.entities.UserEntity;
import com.opdar.athena.mapper.MessageMapper;
import com.opdar.athena.mapper.ProjectMapper;
import com.opdar.athena.messages.TransferMessage;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by shiju on 2017/6/29.
 */
@MessageType(value = TransferMessage.class,type = com.opdar.athena.base.MessageType.TRANSFER)
public class TransferController {
    @Autowired
    TcpSessionManager tcpSessionManager;
    @Autowired
    RedisSessionManager redisSessionManager;
    @Autowired
    MessageMapper messageMapper;
    @Autowired
    ProjectMapper projectMapper;

    @Commond("Transfer")
    public Object transfer(IoSession session,TransferMessage transferMessage) {
        MessageEntity message = new MessageEntity();
        message.setId(transferMessage.getMessageId());
        message = messageMapper.selectOne(message);
        String token = transferMessage.getToken();
        IoSession targetSession = tcpSessionManager.get(token);
        UserEntity user = redisSessionManager.get(token);
        ProjectEntity project = new ProjectEntity();
        project.setAppId(user.getAppId());
        project = projectMapper.selectOne(project);
        if(targetSession != null){
            final MessageEntity finalMessage = message;
            targetSession.write(com.opdar.athena.base.MessageType.MESSAGE,message,project.getDomain()).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if(channelFuture.isSuccess()){
                        //已发送
                        MessageEntity update = new MessageEntity();
                        update.setStat(2);
                        MessageEntity where = new MessageEntity();
                        where.setId(finalMessage.getId());
                        messageMapper.update(update,where);
                    }
                }
            });
        }else if(user.getPlatform() == 0){
            //tcp
            redisSessionManager.removeToken(token,message.getReciver());
        }
        return null;
    }
}
